﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using MyResKit;
using UnityEditor;
using UnityEngine;

public static class AssetBundleIntroBuilder
{

	static string CreateAssetBundleDirIfNotExists()
	{
		var outputPath = Application.streamingAssetsPath + "/AssetBundles/";

		if (!Directory.Exists(outputPath))
		{
			Directory.CreateDirectory(outputPath);
		}

		return outputPath;
	}

	[MenuItem("13.AssetBundleIntro/Build Assets")]
	public static void BuildAssets()
	{
		var outputPath = CreateAssetBundleDirIfNotExists();

		BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.ChunkBasedCompression,
			BuildTarget.StandaloneOSXUniversal);
	}

	[MenuItem("13.AssetBundleIntro/Generate Asset Table")]
	static void GenerateAssetTable()
	{
		var assetBundleNames = AssetDatabase.GetAllAssetBundleNames();

		var assstTable = new AssetTable();

		foreach (var assetBundleName in assetBundleNames)
		{
			var assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);

			var assetBundleInfo = new AssetBundleInfo()
			{
				AssetBundleName = assetBundleName
			};

			foreach (var assetName in assetNames)
			{
				var assetInfo = new AssetInfo()
				{
					OwnerAssetBundleName = assetBundleName,
					AssetName = assetName.GetFileName()
				};

				assetBundleInfo.AssetInfos.Add(assetInfo);
			}

			assstTable.AssetBundleInfos.Add(assetBundleInfo);
		}


		var jsonConent = JsonUtility.ToJson(assstTable, true);

		var path = CreateAssetBundleDirIfNotExists() + "AssetTable.json";
		
		File.WriteAllText(path, jsonConent);
	}

	static string GetFileName(this string assetPath)
	{
		int lastIndexOf = assetPath.LastIndexOf("/");
		int indexOfDot = assetPath.LastIndexOf(".");
		return assetPath.Substring(lastIndexOf + 1, indexOfDot - lastIndexOf - 1);
	}
}
